<?php


/**
 * This is the model class for table "zy_pushnote".
 *
 * The followings are the available columns in table 'zy_pushnote':
 * @property integer $pushid
 * @property string $create_user
 * @property string $content
 * @property string $platform
 * @property string $application
 * @property string $remarks
 * @property integer $delete
 */
class Pushnote extends CActiveRecord {
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Pushnote the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent :: model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'zy_pushnote';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array (
			array (
				'delete',
				'numerical',
				'integerOnly' => true
			),
			array (
				'create_user,title,description, content, platform, application, remarks',
				'length',
				'max' => 255
			),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array (
				'pushid, create_user,title,description,content, platform, application, remarks, delete',
				'safe',
				'on' => 'search'
			),
			
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array ();
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array (
			'pushid' => yii :: t('base', 'Pushid'),
			'create_user' => yii :: t('base', 'Create User'),
			'title' => yii :: t('base', 'Title'),
			'description' => yii :: t('base', 'Description'),
			'content' => yii :: t('base', 'Content'),
			'platform' => yii :: t('base', 'Platform'),
			'application' => yii :: t('base', 'Applications'),
			'remarks' => yii :: t('base', 'Remarks'),
			'delete' => yii :: t('base', 'Delete'),
			
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search() {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('pushid', $this->pushid);
		$criteria->compare('create_user', $this->create_user, true);
		$criteria->compare('title', $this->title, true);
		$criteria->compare('description', $this->description, true);
		$criteria->compare('content', $this->content, true);
		$criteria->compare('platform', $this->platform, true);
		$criteria->compare('application', $this->application, true);
		$criteria->compare('remarks', $this->remarks, true);
		$criteria->compare('delete', $this->delete);

		return new CActiveDataProvider($this, array (
			'criteria' => $criteria,
			
		));
	}
	//查找android google要推送通知的人
	public function getsendid($platform, $app_id) {
		$arr = array ();
		$appid = str_replace("|", ",", $app_id);	
//		$appuser = Appuser :: model()->findAll('platform=:platform and app_id=:app_id', array (
//			':platform' => $platform,
//			':app_id' => $app_id,
//			
//		));
		$sql="select * from zy_appuser where platform=$platform and app_id in($appid)";
		$appuser=Yii::app()->db->createCommand($sql)->queryAll();
		for ($i = 0; $i < count($appuser); $i++) {
			$arr[$i] = $appuser[$i]['send_id'];
		}
		return $arr;

	}
	
	
	//发送android google通知
//	public function sendAndroidgooglenote($send_id, $content,$model) {
//		$url = 'https://android.googleapis.com/gcm/send';
//		//$serverApiKey=array();
//		$application_id = str_replace("|", ",", $model->application);
//		//$application=Application::model()->findByPk($model->application);
//		$sql="select * from zy_application where application_id in($application_id)";
//		$serverApiKeyArr=Yii::app()->db->createCommand($sql)->queryAll();
//		for ($i = 0; $i < count($serverApiKeyArr); $i++) {
//			$serverApiKey[$i] = $serverApiKeyArr[$i]['application_server_key'];
//		}
//		//$serverApiKey = "AIzaSyC7xG7xYS_UpFCw9ZstJpqX-4fM-28kUQ4";
//		//$serverApiKey = $application->application_server_key;
//		$data = array (
//		'registration_ids' => $send_id,
//		// 'registration_ids' =>array($reg,$reg),
//		'data' => array (
//			't'=>$model->title,
//			'd'=>$model->description,
//			'm' => $content
//		)
//		);
//		//print(json_encode($data));
//		$headers = array (
//			'Authorization: key=' . $serverApiKey,
//			'Content-Type: application/json'
//		);
//
//		$ch = curl_init();
//
//		// Set the url, number of POST vars, POST data
//		curl_setopt($ch, CURLOPT_URL, $url);
//		curl_setopt($ch, CURLOPT_POST, true);
//		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//		// Disabling SSL Certificate support temporarly
//		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
//
//		// Execute post
//		$result = curl_exec($ch);
//
//		if ($result === FALSE) {
//			die('Problem occurred: ' . curl_error($ch));
//		} 
//		else {
//			$pushmodel=new Pushnote;
//			$pushmodel=$model;
//			$pushmodel->save();
//		}
//
//		curl_close($ch);
//		echo "response is " . $result;
//	}


	public function sendAndroidgooglenote($send_id, $content,$model) {
		$url = 'https://android.googleapis.com/gcm/send';
		$flg=0;
		$application_id = explode('|',$model->application);
		$arrsendid=array();
		for($i=0;$i<count($application_id);$i++){
			$sqlsendid="SELECT * FROM zy_appuser WHERE app_id=$application_id[$i]";
			$resultsendid=Yii::app()->db->createCommand($sqlsendid)->queryAll();//可能是一个数组
			if(count($resultsendid)==0)
			{
			continue;
			}else{
			for ($j = 0; $j < count($resultsendid); $j++) {
			$arrsendid[$j] = $resultsendid[$j]['send_id'];	
			}
			}
			//通过应用的id找到application_server_key
			$resultapplicationServerkey=Application::model()->findByPk($application_id[$i]);
			$data = array (
			'registration_ids' => $arrsendid,
			'data' => array (
			't'=>$model->title,
			'd'=>$model->description,
			'm' => $content
		)
		);
		$headers = array (
			'Authorization: key=' . $resultapplicationServerkey->application_server_key,
			'Content-Type: application/json'
		);

		$ch = curl_init();

		// Set the url, number of POST vars, POST data
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		// Disabling SSL Certificate support temporarly
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

		// Execute post
		$result = curl_exec($ch);

		if ($result === FALSE) {
			die('Problem occurred: ' . curl_error($ch));
		} 
		curl_close($ch);
		//echo "response is " . $result;
		}
		//最后保存这条数据
		$pushmodel=new Pushnote;
		$pushmodel=$model;
		$pushmodel->save();
	}


	//发送ios google通知
	public function sendIosgooglenote($send_id, $content,$model) {
			$application_id = explode('|',$model->application);
			$arrsendid=array();
			for($i=0;$i<count($application_id);$i++){
			$sqlsendid="SELECT * FROM zy_appuser WHERE app_id=$application_id[$i]";
			$resultsendid=Yii::app()->db->createCommand($sqlsendid)->queryAll();//可能是一个数组
			if(count($resultsendid)==0)
			{
			continue;
			}else{
			for ($j = 0; $j < count($resultsendid); $j++) {
			$arrsendid[$j] = $resultsendid[$j]['send_id'];	
			}
			}
			//通过应用的id找到application_server_key
			$resultapplicationmodel=Application::model()->findByPk($application_id[$i]);
			$message = $content;
			$ctx = stream_context_create();
			stream_context_set_option($ctx, 'ssl', 'local_cert',dirname(Yii::app()->BasePath).'/uploadfiles/apppush/pem/'.$resultapplicationmodel->pem_file);
			stream_context_set_option($ctx, 'ssl', 'passphrase', $resultapplicationmodel->pem_password);
			// Open a connection to the APNS server
			$fp = stream_socket_client(
			'ssl://gateway.sandbox.push.apple.com:2195', $err,
			$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

			if (!$fp)
			exit("Failed to connect: $err $errstr" . PHP_EOL);
			//echo 'Connected to APNS' . PHP_EOL;
			//Create the payload body
			$body['aps'] = array(
			'alert' => $message,
			'sound' => 'default'
			);
			// Encode the payload as JSON
			$payload = json_encode($body);
			for($k=0;$k<count($arrsendid);$k++)
			{
				$msg = chr(0) . pack('n', 32) . pack('H*', $arrsendid[$k]) . pack('n', strlen($payload)) . $payload;
				// Send it to the server
				$result = fwrite($fp, $msg, strlen($msg));
			}
			if (!$result)
				die('Message not delivered' . PHP_EOL);
//			else
//				echo 'Message successfully delivered' . PHP_EOL;			
			// Close the connection to the server
			fclose($fp);
		}
	}
}